package com.erps.CommonUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.erps.db.DBManager;

public class AppManager {
	private static final Logger log = LoggerFactory.getLogger(AppManager.class);

	public static String GetDateTime() {
		return DBManager.ServerDateTime();
	}

	public static String getRemoteIpAddr(HttpServletRequest request) {
		if (request != null) {
			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			return ip;
		} else {
			return "127.0.0.1";
		}
	}

	public static int getWordCount(String cKeyWord) {
		List<String> aKeys = new ArrayList<String>();
		String[] Keys = cKeyWord.split("\\|");
		int iKeyLength = Keys.length;
		for (int k = 0; k < iKeyLength; k++) {
			String cWord = Keys[k];
			if (aKeys.indexOf(cWord) == -1) {
				aKeys.add(cWord);
			}
		}
		return aKeys.size();
	}

	public static String getUTF8(String cStr) {
		cStr = (cStr == null) ? "" : cStr.trim();
		try {
			return new String(cStr.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			return cStr;
		}
	}

	public static String getURLDecoder(String cStr) {
		String cFieldValue = (cStr == null) ? "" : cStr.trim();

		if (cFieldValue.length() > 0)
			try {
				cFieldValue = URLDecoder.decode(cStr, "utf-8");
			} catch (UnsupportedEncodingException e) {
				log.error(e.getMessage());
			}
		return cFieldValue;
	}

	public static String getURLEncoder(String cStr) {
		String cFieldValue = (cStr == null) ? "" : cStr.trim();
		if (cFieldValue.length() > 0)
			try {
				cFieldValue = URLEncoder.encode(cStr, "utf-8");
			} catch (UnsupportedEncodingException e) {
				log.error(e.getMessage());
			}
		return cFieldValue;
	}

	public static String getASKey(int iASKey) {
		return getASKey(String.valueOf(iASKey));
	}

	public static String getASKey(String cASKey) {
		if (cASKey.equals("1"))
			return "分类";
		if (cASKey.equals("2"))
			return "聚合";
		if (cASKey.equals("3"))
			return "微博";
		return "";
	}

	public static int QueryCount(String cDBTableName, String cWhereParm) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select count(1)");
		sql.append(" from " + cDBTableName);
		if (StringEx.getStr(cWhereParm).length() > 0)
			sql.append(" where " + cWhereParm);
		String cv = DBManager.GetStrValue(sql.toString());
		return StringEx.getInt(cv.toString());
	}

	public static List<Map<String, String>> QueryData(String cDBTableName, String cFieldList, String cWhereParm, String cOrderParm, int iPageCount, int iPageNO, int iPageSize) {
		if (iPageNO > iPageCount)
			iPageNO = iPageCount;
		StringBuffer sql = new StringBuffer();
		sql.append(" select " + cFieldList);
		sql.append(" from " + cDBTableName);
		if (StringEx.getStr(cWhereParm).length() > 0)
			sql.append(" where " + cWhereParm);
		if (StringEx.getStr(cOrderParm).length() > 0)
			return DBManager.QueryData(sql.toString(), " order by " + cOrderParm, iPageNO, iPageSize);
		else
			return DBManager.QueryData(sql.toString(), "", iPageNO, iPageSize);
	}

	public static String getSqlSubStr(String cStr, int iStart, int iLength) {
		String cSubStr = Config.ReadString(AppConfig.SQL_SUBSTR, AppConfig.SQL_SUBSTR_DEF);
		return cSubStr.replace("{X}", cStr).replace("{S}", String.valueOf(iStart)).replace("{L}", String.valueOf(iLength));
	}

	public static String replaceKeyWord(String cText, String cWord) {
		cText = StringEx.getStr(cText);
		cWord = StringEx.getStr(cWord);
		if (cWord.length() == 0)
			return cText;
		cWord = cWord.replace("  ", " ").replace("(", " ").replace(")", " ").replace("+", " ").replace("-", " ").replace("|", " ").replace(",", " ");
		String[] keys = cWord.split(" ");
		int iLength = (keys == null) ? 0 : keys.length;
		for (int i = 0; i < iLength; i++) {
			String cKey = keys[i];
			if (cKey.length() > 0) {
				cText = cText.replaceAll("(?i)" + cKey, "<font class='mark_word'>" + cKey + "</font>");
			}
		}
		return cText;
	}

	public static String Explain(HttpSession session, String AStr) {
		String AValue = AStr;
		Date vDate = new Date();

		AValue = ReplaceStr(AValue, "{YYYY}", DateUtils.getDateStr(vDate, "YYYY"));
		System.out.println(AValue);
		AValue = ReplaceStr(AValue, "{YY}", DateUtils.getDateStr(vDate, "YY"));
		System.out.println(AValue);
		AValue = ReplaceStr(AValue, "{MM}", DateUtils.getDateStr(vDate, "MM"));
		System.out.println(AValue);
		AValue = ReplaceStr(AValue, "{DD}", DateUtils.getDateStr(vDate, "dd"));
		System.out.println(AValue);
		String cOrgID = StringEx.getStr(session.getAttribute(AppConfig.SESSION_ORGID));
		String cUserID = StringEx.getStr(session.getAttribute(AppConfig.SESSION_USERID));
		AValue = ReplaceStr(AValue, "{orgid}", cOrgID);
		AValue = ReplaceStr(AValue, "{userid}", cUserID);
		return AValue;
	}

	public static String replaceDayInfo(String cStr) {
		String CurDay = DateUtils.getDay();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date vDate = null;
		try {
			vDate = sdf.parse(CurDay);
			Calendar calendar = Calendar.getInstance();// 日历对象
			calendar.setTime(vDate);// 设置当前日期
			calendar.add(Calendar.HOUR, -20);// 月份减一
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String cYear = CurDay.substring(0, 4);
		String cMonth = CurDay.substring(5, 7);
		String cDay = CurDay.substring(8, 10);

		cStr = cStr.replace("{YYYY}", cYear);
		cStr = cStr.replace("{YY}", cYear.substring(2));
		cStr = cStr.replace("{MM}", cMonth);
		cStr = cStr.replace("{DD}", cDay);
		return cStr;
	}

	public static String GB2312toUTF8(String oldStr) {
		String cNewStr = "";
		try {
			byte[] vByte = oldStr.getBytes("GB2312");
			cNewStr = new String(vByte, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			cNewStr = oldStr;
		}
		return cNewStr;
	}

	public static String GBKtoUTF8(String oldStr) {
		String cNewStr = "";
		try {
			byte[] vByte = oldStr.getBytes("GBK");
			cNewStr = new String(vByte, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			cNewStr = oldStr;
		}
		return cNewStr;
	}

	public synchronized static String GUID() {
		UUID arKey = UUID.randomUUID();
		return arKey.toString().toUpperCase();
	}

	public static void Alert(String Message) {
		try {
			// HttpServletResponse response =
			// ServletActionContext.getResponse();
			// PrintWriter out = response.getWriter();
			// out.print("<script language=JavaScript>");
			// out.println("<!--");
			// out.println("alert('" + Message + "')");
			// out.println("--!>");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getDictionarySQL(String cTypeID) {
		StringBuffer sql = new StringBuffer();
		sql.append("select keyname,keyid ");
		sql.append(" from s_dictionarys ");
		sql.append("where typeid='" + cTypeID + "'");
		return sql.toString();
	}

	public static String getDictionarySQLExt(String cTypeID) {
		StringBuffer sql = new StringBuffer();
		sql.append("select keyname,extkey as keyid");
		sql.append(" from s_dictionarys ");
		sql.append("where typeid='" + cTypeID + "'");
		return sql.toString();
	}

	public static String getDictionaryValue(String cTypeID, String cValue) {
		StringBuffer sql = new StringBuffer();
		sql.append("select keyname");
		sql.append(" from s_dictionarys ");
		sql.append(" where typeid='" + cTypeID + "'");
		sql.append(" and keyid='" + cValue + "'");
		return DBManager.GetStrValue(sql.toString());
	}

	public static String getDictionaryValueExt(String cTypeID, String cValue) {
		StringBuffer sql = new StringBuffer();
		sql.append("select keyname");
		sql.append(" from s_dictionarys ");
		sql.append(" where typeid='" + cTypeID + "'");
		sql.append(" and extkey='" + cValue + "'");

		return DBManager.GetStrValue(sql.toString());
	}

	public static HttpSession getLoginSession(HttpServletRequest request) {
		try {
			return request.getSession();
		} catch (Exception ex) {
			return null;
		}
	}

	public boolean isAuthor(HttpSession session) {
		if (session == null)
			return false;

		if (session.getAttribute(AppConfig.SESSION_USERID) != null)
			return true;
		else
			return false;
	}

	public static String getUserID(HttpSession session) {
		if (session == null)
			return "";

		if (session.getAttribute(AppConfig.SESSION_USERID) != null)
			return session.getAttribute(AppConfig.SESSION_USERID).toString();
		else
			return "";
	}

	public static String getUserName(HttpSession session) {
		if (session == null)
			return "";

		if (session.getAttribute(AppConfig.SESSION_USERNAME) != null)
			return session.getAttribute(AppConfig.SESSION_USERNAME).toString();
		else
			return "";
	}

	public static String getUnitName(HttpSession session) {
		if (session == null)
			return "";

		if (session.getAttribute(AppConfig.SESSION_ORGNAME) != null)
			return session.getAttribute(AppConfig.SESSION_ORGNAME).toString();
		else
			return "";
	}

	public static String getUserName(String cUserID) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select username ");
		sql.append(" from s_userlist ");
		sql.append(" where userid='" + cUserID + "'");
		return DBManager.GetStrValue(sql.toString());
	}

	public static String getTitle(int cNodeID) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select nodename ");
		sql.append(" from s_nodes ");
		sql.append(" where code like '" + cNodeID + "%'");
		sql.append(" order by orderby ");
		List<Map<String, String>> rows = DBManager.QueryData(sql.toString());
		String Title = "";
		for (int i = 0; i < rows.size(); i++) {
			Map<String, String> row = rows.get(i);
			if (Title.equals(""))
				Title = row.get("nodename").toString();
			else
				Title = Title + "-" + row.get("nodename").toString();
		}
		return Title;
	}

	public static String ReplaceStr(String ASourceStr, String AReplaceStr, String ATargetStr) {
		StringBuffer AStr = new StringBuffer();
		int iPos = ASourceStr.indexOf(AReplaceStr);
		if (iPos > -1) {
			AStr.append(ASourceStr.substring(0, iPos));
			AStr.append(ATargetStr);
			AStr.append(ASourceStr.substring(iPos + AReplaceStr.length()));
			return AStr.toString();
		} else
			return ASourceStr;
	}

	public static String getOrgID(HttpSession session) {
		try {
			return (String) session.getAttribute(AppConfig.SESSION_ORGID);
		} catch (Exception ex) {
			return "";
		}
	}

	public static String getOrgName(HttpSession session) {
		try {
			return (String) session.getAttribute(AppConfig.SESSION_ORGNAME);
		} catch (Exception ex) {
			return "";
		}
	}

	public static String getOrgName(String cOrgID) {
		return DBManager.GetStrValue("select orgshortname from s_orginf where orgid='" + cOrgID + "'");
	}

	public static String ByteToString(byte[] chs) {
		String outputStr = new String(chs);
		return outputStr;
	}

	public static String getAppService() {
		String cHost = "";
		String cPort = "";
		cHost = DBConfig.getSysKey(AppConfig.CLOUD_HOST, cHost);
		cPort = DBConfig.getSysKey(AppConfig.CLOUD_PORT, cPort);
		if (StringEx.getStr(cHost).length() > 0) {
			if (StringEx.getStr(cPort).length() == 0)
				cPort = "80";
			String cUrl = "http://" + cHost + ":" + cPort + "/cloudservice/dbservice/";
			return cUrl;
		} else {
			return "";
		}
	}

}
